﻿using IOA.MES.Business;
using IOA.MES.DataAccess.Enum;
using IOA.MES.DataAccess.VModel;
using IOA.MES.PdaApi.Models.Request.Allocate;
using IOA.MES.PdaApi.Models.Response.Allocate;
using IOA.Utils;
using System;
using System.Linq;
using System.Web.Http;

namespace IOA.MES.PdaApi.Controllers
{
    /// <summary>
    /// 调拨管理
    /// </summary>
    public class AllocateController : ApiController
    {
        /// <summary>
        /// 获取调拨单信息
        /// </summary>
        [HttpPost]
        public ResultJson<GetAllocateResponse> GetAllocate([FromBody] GetAllocateRequest request)
        {
            request.AllocateNo = request.AllocateNo.IndexOf("|") < 0 ? request.AllocateNo : request.AllocateNo.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries).LastOrDefault();
            var allocate = new AllocateOrderMgr().GetAllocateOrder(request.AllocateNo);
            if (allocate == null)
            {
                return new ResultJson<GetAllocateResponse>(new GetAllocateResponse { AllocateOrder = null });
            }
            //if (!StringUtils.Equals(allocate.ToWarehouseCode, BaseEnv.WarehouseCode))
            //{
            //    return new ResultJson<GetAllocateResponse>(403, $"Kho nhận hàng không khớp, vui lòng chuyển sang kho sau\r\n收货仓库不匹配，请切换至如下仓库\r\nThe receiving warehouse does not match, please switch to the following warehouse\r\n{allocate.ToWarehouse}");
            //}
            return new ResultJson<GetAllocateResponse>(new GetAllocateResponse
            {
                AllocateOrder = allocate == null ? null : new AllocateOrder
                {
                    AllocateNo = allocate.AllocateNo,
                    AllocateTime = allocate.AllocateTime,
                    FromWarehouse = allocate.FromWarehouse,
                    FromWarehouseCode = allocate.FromWarehouseCode,
                    Remark = allocate.Remark,
                    ReviewTime = allocate.ReviewTime,
                    ToWarehouse = allocate.ToWarehouse,
                    ToWarehouseCode = allocate.ToWarehouseCode,
                    UpdateTime = allocate.UpdateTime,
                    WorkOrderNo = allocate.WorkOrderNo
                }
            });
        }

        /// <summary>
        /// 调拨收货
        /// </summary>
        [HttpPost]
        public ResultJson<AllocateInboundResponse> AllocateInbound([FromBody] AllocateInboundRequest request)
        {
            var user = BaseEnv.User;
            request.AllocateNo = request.AllocateNo.IndexOf("|") < 0 ? request.AllocateNo : request.AllocateNo.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries).LastOrDefault();
            var allocate = new AllocateOrderMgr().GetAllocateOrder(request.AllocateNo);
            if (allocate == null)
            {
                return new ResultJson<AllocateInboundResponse>(500, $"Lệnh chuyển không tồn tại\r\n调拨单不存在\r\nThe transfer order does not exist");
            }

            //if (!StringUtils.Equals(allocate.ToWarehouseCode, BaseEnv.WarehouseCode))
            //{
            //    return new ResultJson<AllocateInboundResponse>(403, $"Kho nhận hàng không khớp, vui lòng chuyển sang kho sau\r\n收货仓库不匹配，请切换至如下仓库\r\nThe receiving warehouse does not match, please switch to the following warehouse\r\n{allocate.ToWarehouse}");
            //}
            var model = new VInbound
            {
                CreateBy = user.PkId,
                InboundType = InboundType.AllocateInbound,
                InboundTypeNo = allocate.AllocateNo,
                WarehouseCode = allocate.ToWarehouseCode,
                WarehouseName = allocate.ToWarehouse
            };

            var total = 0;
            var batchNos = request.Products.Select(_ => _.BatchNo).Distinct().ToList();
            var allocateProducts = new AllocateOrderMgr().QueryAllocateProducts(1, 0, out total, allocate.AllocateNo).Where(_ => batchNos.Contains(_.BatchNo, StringComparer.CurrentCultureIgnoreCase)).ToList();
            if (batchNos.Any(_ => !allocateProducts.Select(p => p.BatchNo).Contains(_)))
            {
                return new ResultJson<AllocateInboundResponse>(1, $"下列批次号不存在：{string.Join("、", batchNos.Where(_ => !allocateProducts.Select(p => p.BatchNo).Contains(_)))}");
            }
            var products = request.Products.Select(product => new VInboundProduct
            {
                ProductCode = allocateProducts.FirstOrDefault(_ => string.Equals(product.BatchNo, _.BatchNo, StringComparison.CurrentCultureIgnoreCase))?.ProductCode,
                ProductName = allocateProducts.FirstOrDefault(_ => string.Equals(product.BatchNo, _.BatchNo, StringComparison.CurrentCultureIgnoreCase))?.ProductName,
                CreateBy = user.PkId,
                InventoryType = InventoryType.Mterial,
                BatchNo = product.BatchNo,
                ReceiveQuantity = product.Quantity,
                WarehouseCode = allocate.ToWarehouseCode,
                WarehouseName = allocate.ToWarehouse
            }).ToList();

            new InboundMgr().Inbound(model, products);
            return new ResultJson<AllocateInboundResponse>();
        }

        /// <summary>
        /// 获取调拨产品信息
        /// </summary>
        [HttpPost]
        public ResultJson<GetAllocateProductResponse> GetAllocateProduct([FromBody] GetAllocateProductRequest request)
        {
            request.AllocateNo = request.AllocateNo.IndexOf("|") < 0 ? request.AllocateNo : request.AllocateNo.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries).LastOrDefault();
            var product = new AllocateOrderMgr().GetAllocateProduct(request.AllocateNo, request.BatchNo);
            return new ResultJson<GetAllocateProductResponse>(product == null ? null : new GetAllocateProductResponse
            {
                BatchNo = product.BatchNo,
                ProductCode = product.ProductCode,
                ProductName = product.ProductName,
                Quantity = product.Quantity
            });
        }

        /// <summary>
        /// 查询调拨收货记录
        /// </summary>
        [HttpPost]
        public ResultJson<QueryAllocateInboundsResponse> QueryAllocateInbounds([FromBody] QueryAllocateInboundsRequest request)
        {
            var total = 0;
            var inbounds = new InboundMgr().QueryInbounds(request.PageIndex, request.PageSize, out total, "", InboundType.AllocateInbound, null, null, BaseEnv.User.PkId);
            return new ResultJson<QueryAllocateInboundsResponse>(new QueryAllocateInboundsResponse
            {
                Inbounds = inbounds.Select(_ => new AllocateInboundOrder
                {
                    WarehouseCode = _.WarehouseCode,
                    WarehouseName = _.WarehouseName,
                    Quantity = _.Products.Count,
                    InboundBy = _.CNCreateBy,
                    AllocateNo = _.InboundTypeNo,
                    InboundNo = _.InboundNo,
                    InboundTime = _.CreateTime,
                    Products = _.Products.Select(p => new AllocateProduct
                    {
                        Quantity = p.ReceiveQuantity,
                        BatchNo = p.BatchNo,
                        ProductCode = p.ProductCode,
                        ProductName = p.ProductName
                    }).ToList()
                }).ToList()
            }, total);
        }

        /// <summary>
        /// 获取调拨收货详情
        /// </summary>
        [HttpPost]
        public ResultJson<GetAllocateInboundResponse> GetAllocateInbound([FromBody] GetAllocateInboundRequest request)
        {
            var inbound = new InboundMgr().GetInbound(request.InboundNo);
            return new ResultJson<GetAllocateInboundResponse>(new GetAllocateInboundResponse
            {
                AllocateInbound = inbound == null ? null : new AllocateInboundOrder
                {
                    InboundBy = inbound.CNCreateBy,
                    InboundNo = inbound.InboundNo,
                    AllocateNo = inbound.InboundTypeNo,
                    InboundTime = inbound.CreateTime,
                    WarehouseCode = inbound.WarehouseCode,
                    WarehouseName = inbound.WarehouseName,
                    Quantity = inbound.Products.Count,
                    Products = inbound.Products.Select(p => new AllocateProduct
                    {
                        Quantity = p.ReceiveQuantity,
                        BatchNo = p.BatchNo,
                        ProductCode = p.ProductCode,
                        ProductName = p.ProductName
                    }).ToList()
                }
            });
        }

        /// <summary>
        /// 获取发料产品信息
        /// </summary>
        [HttpPost]
        public ResultJson<GetDispatchProductResponse> GetDispatchProduct([FromBody] GetDispatchProductRequest request)
        {
            var product = new AllocateOrderMgr().GetDispatchProduct(request.WorkOrderNo, request.BatchNo);
            return new ResultJson<GetDispatchProductResponse>(new GetDispatchProductResponse
            {
                Product = product == null ? null : new BatchProduct
                {
                    BatchNo = product.BatchNo,
                    ProductCode = product.ProductCode,
                    ProductName = product.ProductName
                }
            });
        }

        /// <summary>
        /// 车间发料
        /// </summary>
        [HttpPost]
        public ResultJson<DispatchResponse> Dispatch([FromBody] DispatchRequest request)
        {
            new AllocateOrderMgr().Dispatch(new VDispatchOrder
            {
                WorkOrderNo = request.WorkOrderNo,
                ReceiveBy = request.ReceiveBy,
                CreateBy = BaseEnv.User.PkId,
                Products = request.Products.Select(_ => new VDispatchOrderProduct
                {
                    BatchNo = _.BatchNo,
                    Quality = _.Quality
                }).ToList()
            });
            return new ResultJson<DispatchResponse>();
        }

        /// <summary>
        /// 查询车间发料记录
        /// </summary>
        [HttpPost]
        public ResultJson<QueryDispatchOrdersResponse> QueryDispatchOrders([FromBody] QueryDispatchOrdersRequest request)
        {
            var total = 0;
            var dispatchOrders = new AllocateOrderMgr().QueryDispatchOrders(request.PageIndex, request.PageSize, out total, BaseEnv.User.PkId);
            return new ResultJson<QueryDispatchOrdersResponse>(new QueryDispatchOrdersResponse
            {
                DisapatchOrders = dispatchOrders.Select(_ => new DisapatchOrder
                {
                    WorkOrderNo = _.WorkOrderNo,
                    DispatchNo = _.DispatchNo,
                    DispatchTime = _.CreateTime,
                    ReceiveBy = _.ReceiveBy,
                    WorkshopName = _.WorkshopName
                }).ToList()
            });
        }

        /// <summary>
        /// 获取发料单对象
        /// </summary>
        [HttpPost]
        public ResultJson<GetDispatchOrderResponse> GetDispatchOrder([FromBody] GetDispatchOrderRequest request)
        {
            var dispatchOrder = new AllocateOrderMgr().GetDispatchOrder(request.DispatchNo);
            return new ResultJson<GetDispatchOrderResponse>(new GetDispatchOrderResponse
            {
                DisapatchOrder = dispatchOrder == null ? null : new DisapatchOrder
                {
                    DispatchNo = dispatchOrder.DispatchNo,
                    DispatchTime = dispatchOrder.CreateTime,
                    ReceiveBy = dispatchOrder.ReceiveBy,
                    WorkOrderNo = dispatchOrder.WorkOrderNo,
                    WorkshopName = dispatchOrder.WorkshopName,
                    Products = dispatchOrder.Products.Select(_ => new BatchProduct
                    {
                        BatchNo = _.BatchNo,
                        ProductCode = _.ProductCode,
                        ProductName = _.ProductName,
                        Quality = _.Quality,
                    }).ToList()
                }
            });
        }
    }
}
